package com.idanchuang.component.mq.amqp.switcher.apollo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;

/**
 * @author yjy
 * Created at 2021/8/9 6:19 下午
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ApolloConsumeSwitcherRunner implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(ApolloConsumeSwitcherRunner.class);
    private final ApolloConsumeSwitcher apolloConsumeSwitcher;
    private final RabbitListenerEndpointRegistry registry;

    public ApolloConsumeSwitcherRunner(ApolloConsumeSwitcher apolloConsumeSwitcher,
                                       RabbitListenerEndpointRegistry registry) {
        this.apolloConsumeSwitcher = apolloConsumeSwitcher;
        this.registry = registry;
    }

    @Autowired
    private Environment environment;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (registry == null) {
            logger.warn("ApolloConsumeSwitcher init failed, registry is null");
            return;
        }
        String initConfig = environment.getProperty(ApolloConsumeSwitcher.STOP_CONSUME_KEY);
        // init container map
        apolloConsumeSwitcher.init(registry.getListenerContainers(), initConfig);
    }
}
